package com.dongdongshop.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Autowired DefaultWebSecurityManager securityManager){
        //创建过滤工厂链
        ShiroFilterFactoryBean filterFactoryBean = new ShiroFilterFactoryBean();
        //添加shiro 内置的过滤器
        /*
         *常用的过滤器
         * anon:不需要登陆就可以访问
         * authc:必须登录才能访问
         *
         * perms:登陆之后还要有权限才能访问
         * logout:推出登录
         * */
        Map<String,String> filterMap = new LinkedHashMap<>();
//        filterMap.put("/**","authc");
        filterMap.put("/logout","logout");

        filterMap.put("/cartController/togetOrderInfo","authc");
        filterMap.put("/cartController/toHome","authc");
        filterMap.put("/cartController/toHomeAddress","authc");
        filterMap.put("/**","anon");

        filterFactoryBean.setFilterChainDefinitionMap(filterMap);
        //shiro默认登陆页面为login.jsp 我们的dubbo不支持jsp页面 所以我们要修改登陆页面
        filterFactoryBean.setLoginUrl("/login");
        //没有权限设置跳转显示页面
//        filterFactoryBean.setUnauthorizedUrl("/unauthorized");
        filterFactoryBean.setSecurityManager(securityManager);
        return filterFactoryBean;
    }

    //shiro的安全管理器
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Autowired LoginRealm realm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(realm);
        return securityManager;
    }

    @Bean
    public LoginRealm loginRealm(@Autowired HashedCredentialsMatcher matcher){
        LoginRealm realm = new LoginRealm();
        realm.setCredentialsMatcher(matcher);
        return realm;
    }
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher(){
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("MD5");
        matcher.setHashIterations(3);
        matcher.setStoredCredentialsHexEncoded(true);
        return matcher;
    }

    //配置ShiroDialect 和thymeleaf配合使用
    @Bean
    public ShiroDialect shiroDialect(){
        ShiroDialect shiroDialect = new ShiroDialect();
        return shiroDialect;
    }
}
